package com.cong._189;

import java.util.*;

class Solution {
    public void rotate(int[] nums, int k) {
        int len = nums.length;
        int step = k % len;
        if(step == 0) return;

        // step = 2;
        // 1, 2, 3, 4, 5, 6, 7; tmp = 1; targetIndex = 2; target = 3;
        // 1, 2, 1, 4, 5, 6, 7; tmp = 3; targetIndex = 4; target = 5;
        // 1, 2, 1, 4, 3, 6, 7; tmp = 5; targetIndex = 6; target = 7;
        // 1, 2, 1, 4, 3, 6, 5; tmp = 7; targetIndex = 1; target = 2;
        // 1, 7, 1, 4, 3, 6, 5; tmp = 2; targetIndex = 3; target = 4;
        // 1, 7, 1, 2, 3, 6, 5; tmp = 4; targetIndex = 5; target = 6;

        // tmp = target; targetIndex = (targetIndex + step) % len; target = nums[targetIndex]

        int tmp, targetIndex, target, circleStart;
        tmp = nums[0];
        circleStart = nums[0];
        targetIndex = step;
        target = nums[targetIndex];
        int count = 0;
        while(count++ < len) {
            nums[targetIndex] = tmp;
            if(target == circleStart) {
                tmp = nums[targetIndex + 1];
                targetIndex = (targetIndex + 1 + step) % len;
            }else {
                tmp = target;
                targetIndex = (targetIndex + step) % len;
            }
            target = nums[targetIndex];
        }
    }
}


